Conditions | 6 |
Total Lines | 51 |
Code Lines | 45 |
Lines | 0 |
Ratio | 0 % |
Changes | 0 |
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
1 | import React, {useEffect, useState} from "react"; |
||
7 | |||
8 | function SearchPage(): JSX.Element { |
||
9 | const [mediaElements, setMediaElements] = useState<MediaResource[]>([]); |
||
10 | const [searchFieldContent, setSearchFieldContent] = useState(""); |
||
11 | const [query, setQuery] = useState(""); |
||
12 | const [startIndex, setStartIndex] = useState(0); |
||
13 | const [isLoading, setIsLoading] = useState(false); |
||
14 | |||
15 | useEffect(() => { |
||
16 | async function fetchData() { |
||
17 | setIsLoading(true); |
||
18 | const request = await fetch("/api/search", { |
||
19 | method: "POST", |
||
20 | body: JSON.stringify({query: query, startIndex: startIndex, endIndex: startIndex + pageSize}) |
||
21 | }); |
||
22 | |||
23 | if (request.status === 200) { |
||
24 | const response = await request.json(); |
||
25 | setMediaElements(response.documents === null ? [] : response.documents); |
||
26 | setStartIndex(startIndex + pageSize); |
||
27 | } |
||
28 | |||
29 | setIsLoading(false); |
||
30 | } |
||
31 | |||
32 | fetchData(); |
||
33 | }, [query]); |
||
34 | |||
35 | function handleChange(e: React.ChangeEvent<HTMLInputElement>) { |
||
36 | setSearchFieldContent(e.target.value); |
||
37 | } |
||
38 | |||
39 | function handleSearch(e: React.FormEvent) { |
||
40 | e.preventDefault(); |
||
41 | setQuery(searchFieldContent); |
||
42 | setStartIndex(0); |
||
43 | setMediaElements([]); |
||
44 | } |
||
45 | |||
46 | return ( |
||
47 | <React.Fragment> |
||
48 | <form className="top" onSubmit={handleSearch}> |
||
49 | <Form.Control className="m-1" type="text" onChange={handleChange}/> |
||
50 | <Button type="submit" className="m-1">Search</Button> |
||
51 | </form> |
||
52 | |||
53 | <div className="media-flex-container"> |
||
54 | {mediaElements.map(element => <MediaCard key={element._id.toString()} {...element} />)} |
||
55 | {isLoading && <h1>Loading...</h1>} |
||
56 | </div> |
||
57 | </React.Fragment> |
||
58 | ); |
||
62 |